package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserLoginMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ApUserLoginServiceImpl
 * @Description TODO
 * @Author AWei
 * @DATE 2021/4/20 17:23
 * @Version 1.0
 */
@Service
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserLoginMapper, LoginDto> implements ApUserLoginService {

    @Resource
    private ApUserMapper apUserMapper;

    /**
     * @param loginDto app端登录数据封装对象
     * @return 登录结果
     * @Description app端登录
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        Map<String, Object> map = new HashMap<>();
        //1. 校验参数：手机设备id和（手机号、密码）必须存在其一
        if (ObjectUtils.isEmpty(loginDto.getEquipmentId()) && (StringUtils.isBlank(loginDto.getPhone()) || StringUtils.isBlank(loginDto.getPassword()))) {
            CustomException.custom(AppHttpCodeEnum.PARAM_REQUIRE, "缺少登录参数");
        }
        //2. 若手机号和密码都不为null 则进行验证
        if (StringUtils.isNotBlank(loginDto.getPhone()) || StringUtils.isNotBlank(loginDto.getPassword())) {
            // 通过手机号和用户状态查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone())
                    .eq(ApUser::getStatus, 0));
            if (ObjectUtils.isEmpty(apUser)) {
                CustomException.custom(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "手机号或密码错误！");
            }
            String psw = DigestUtils.md5DigestAsHex((loginDto.getPassword() + apUser.getSalt()).getBytes());
            if (!psw.equals(apUser.getPassword())) {
                CustomException.custom(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误！");
            }
            //验证通过，生成用户id的token，并返回结果
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user", apUser);
            map.put("token", AppJwtUtil.getToken(Long.valueOf(apUser.getId())));
            return ResponseResult.okResult(map);
        } else {
            //通过手机设备id访问 生成token并返回结果
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
